import React, { PropTypes, Component } from 'react'
import fetch from 'isomorphic-fetch'
import { Link } from 'react-router'

import Table from './Table'
import NavLink from './NavLink'
import {myAjaxJson,ROOTURL} from './../publicAPI/publicAPI'

class PointMRecord extends Component {

    constructor(props, context) {
        super(props, context)
        console.log("初始化")
        this.state = {
           Recorddata:[],
        };// 初始化状态
          this.page=1;
        this.start=0;
        this.getlist.bind(this);
    }

    componentWillMount() {
        console.log("将安装")
        this.getlist();
    }

    componentDidMount() {
        console.log("安装成功")
    }
      ChangeTimeToString(date){
        let sjdat=new Date(date);

        let year=sjdat.getFullYear();

        let  month=sjdat.getMonth()+1;

        let  day=sjdat.getDate();

        return year+"-"+month+"-"+day;


    }
    getlist(){
        var id=this.props.params.id;
        var Geturl=ROOTURL+'credit/record/search.api'
        var _this=this;
 
         fetch(Geturl, {
            method: 'post',
            // mode : 'no-cors',
            // headers: { 
            //   "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" 
            // }, 
            body:JSON.stringify({ 
                 "where":{
             
              "creditAccount":{
                       "id":[
                             ["eq",id]
                       ]
               },  
             },
              "order":
                [           // ORDER BY  
                    ["tmCreate", "desc"],    // id ASC,
         
                ],
                "limit":10
            
                })
        }).then(res=> {
            if (res.ok) {
                res.json().then(data=> { 
                    console.log(data);
                   _this.setState({
                  Recorddata:data,
                });
            })
            }
        })
    }

   handlePageClick(e) { //1为下一页，2为上一页
        let _buttonValue = e.target.value;
        let id=this.props.params.id;
        let next=document.getElementsByClassName("next")[0];
        let prev=document.getElementsByClassName("prev")[0];
        let _this=this;     
        if (_buttonValue == 1) {
          
          this.start=this.start+10;
          this.page++;
          prev.style.display="block";

        } else {
          this.start=this.start-10;
          this.page--;
          next.style.display="block";
        }
        console.log(this.page);
         
         let params={
             "where":{
             
              "creditAccount":{
                       "id":[
                             ["eq",id]
                       ]
               },

                "dd":[
                    ["eq",false]

                ],

            },
                 "order":
                [           // ORDER BY  
                        ["id", "DESC"],    
             
                ],
                "start":this.start,
                "limit":10
                
        }
        fetch(ROOTURL+'credit/record/search.api',{
                method: 'post',
                headers: {
                    "Content-type": "application/json; charset=UTF-8"
                },
        
                body:JSON.stringify(params)
        }).then(response=>{return response.json()})
        .then(data=>{
            if(data.length<10&&this.page!=1)
             next.style.display="none";
            this.setState({
            Recorddata:data
            });
        }
            //console.log(data);
        )
        if(this.page==1){
       
            prev.style.display="none";
        }             
    }
    handleSearch(){
        var starttime=this.refs.time.value;
        var _this=this;
         var id=this.props.params.id;
        var Geturl=ROOTURL+'credit/record/search.api'
      
    starttime = starttime.replace(new RegExp("-","gm"),"/");
    var starttimeHaoMiao = (new Date(starttime)).getTime();
    console.log(starttimeHaoMiao)
         fetch(Geturl, {
            method: 'post',
            // mode : 'no-cors',
            // headers: { 
            //   "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" 
            // }, 
            body:JSON.stringify({ 
                 "where":{         
              "CreditAccount ":{
                       "id":[
                             ["eq",id]
                       ],
               },  
            "tmCreate":[
                            ["le",starttimeHaoMiao+86400000],
                            ["ge",starttimeHaoMiao]
                     ]
             }
            
                })
        }).then(res=> {
            if (res.ok) {
                res.json().then(data=> {
                    console.log(data);
                   _this.setState({
                  Recorddata:data,
                });
            })
            }
        })
        
    }


    tHead() {
        var data = [
            {name: "日期"},
            {name: "类别"},
            {name: "变化量"},
            {name: "备注"},
            
        ];
        const _headArr = [];
        const _width = {
            "0":"25%",
            "1":"25%",
            "2":"25%",
            "3":"25%",        
         
        };
       
        _headArr.push(data.map((item, index) => <th style={{width: _width[index]}} role="1"
                                                    key={index}>{item.name}</th>));
        return _headArr;
    }

    tBody() {
        var array=new Array();
        var _this=this;
        var i;
        var _data=_this.state.Recorddata
  
    return _data.map((item) => <tr key = {item.id} >

                     
                     < td > { _this.ChangeTimeToString(item.tmCreate) } < /td > 
                      < td > { item.category } < /td > 
                     < td > { item.alter } < /td>
                      < td > { item.note } < /td >  
                     < td > { item.remark } < /td >
                    
        </tr>)

    }

    render() {
        console.log("理发师管理" + "渲染" + this.state.page)
        return (
            	<div className="right-wapper" style={{height: this.state.rHeight}}>
	    		    		<div className="rt-wrap rt-wrap-header">
	    		    			<div className="input-div pr">
	    			    			<label>时间:</label>
	    			    			<input type="text" placeholder="请输入查询时间" className="default-text"
	    			    				ref="time"value={this.state.InputValue}/>
	    			    		</div>
	    			    		
	    			    		<div className="input-div">
	    			    			<button className="search-btn" onClick={(e) => this.handleSearch(e)}>查找</button>
	    			    		</div>
	    			    		
	    		    		</div>
	    		<div className="rt-wrap">
	    			<h3 className="catagory">
	    				<span className="cata-title">积分详细记录</span>
	    				<button className="next" value="1" onClick={(e) => this.handlePageClick(e)}></button>
                        <button style={{display:'none'}}  className="prev" value="2" onClick={(e) => this.handlePageClick(e)}></button>
	    			</h3>
	    			<Table tHead={this.tHead.bind(this)()} tBody={this.tBody.bind(this)()}/>
	    		</div>
	    		
	    	</div>

        )
    }
}

export default PointMRecord
